package com.xpsoft.app.user.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.xpsoft.app.user.UserLoginTypeConst;
import com.xpsoft.app.user.pojo.ClientInfo;
import com.xpsoft.app.user.pojo.PhoneAuthorization;
import com.xpsoft.app.user.pojo.User;
import com.xpsoft.framework.context.ContextHolder;
import com.xpsoft.framework.dao.support.Page;
import com.xpsoft.framework.json.DateJsonValueProcessor;
import com.xpsoft.framework.service.Service;
import com.xpsoft.framework.util.BeanUtil;
import com.xpsoft.framework.util.HttpUtil;
import com.xpsoft.framework.web.adapter.struts2.BaseAction;

public class UserAction extends BaseAction{
	private Service baseService = (Service) ContextHolder.getBean("baseService");
	/**
	 * 判断非法字符
	 * @Methods Name invalidChar
	 * @Create In Sep 7, 2010 By likang
	 * @param param
	 * @return boolean
	 */
	private boolean invalidChar(String param) {
		// TODO Auto-generated method stub
		if (param.contains("'")) {		
			return true;
		} 
		return false;
	}
	
	
	public String  login() throws Exception {
		JSONObject jsonBack = new JSONObject();
		String username = HttpUtil.getString(super.getRequest(), "username");
		String password = HttpUtil.getString(super.getRequest(), "password");
		jsonBack.put("success", false);
		if ((HttpUtil.isNotNullAndEmpty(username) && HttpUtil.isNotNullAndEmpty(password))) {
			Map map = new HashMap<String, String>();
			map.put("deleteflag", 0);
			map.put("username", username);
			map.put("password", password);
			List<User> list = baseService.getObjectsByParam(User.class, map, null, null);
			if (!list.isEmpty()) {
				super.getSession().setAttribute(UserLoginTypeConst.USERINFO, list.get(0));
				jsonBack.put("success", true);
			}
		} 
		PrintWriter pw = super.getPrintWriter();
		pw.append(jsonBack.toString());
		pw.flush();
		return null;
	}
	
	/**
	 * 用户退出
	 * @Methods Name logout
	 * @Create In Aug 20, 2010 By likang
	 * @return
	 * @throws Exception String
	 */
	public String logout() throws Exception{
//		notifyLogout();
		super.getSession().removeAttribute(UserLoginTypeConst.USERINFO);
		PrintWriter pw = super.getPrintWriter();
		pw.append("");
		pw.flush();		
		return "login";
	}
	
	public String  queryPhoneAuth() throws Exception {
		String ip = HttpUtil.getString(super.getRequest(), "ip");
		Map map = new HashMap<String, String>();
		map.put("deleteflag", 0);
		if (StringUtils.isNotEmpty(ip)) {
			map.put("clientIp", ip);
		}
		String cuPage = super.getRequest().getParameter("currentPage");
		Integer currentPage = 1;
		if(cuPage!=null){
			currentPage = Integer.valueOf(cuPage);
		}
		Page page = baseService.findAllByPageMysql(PhoneAuthorization.class,map, "createDate", false, currentPage, 20);
		super.getRequest().setAttribute("page", page); 
		return "queryPhoneAuth";
	}
	
	
	public String  removePhoneAuth() throws Exception {
		String id = super.getRequest().getParameter("id");
		PhoneAuthorization phoneAuthorization = new PhoneAuthorization();
		phoneAuthorization.setId(Long.parseLong(id));
		phoneAuthorization.setDeleteflag(1);
		baseService.update(phoneAuthorization);
		return "queryPhoneAuthIndex";
	}
	
	
	public String  queryClient() throws Exception {
		String name = HttpUtil.getString(super.getRequest(), "name");
		String ip = HttpUtil.getString(super.getRequest(), "ip");
		Map map = new HashMap<String, String>();
		map.put("deleteflag", 0);
//		if (StringUtils.isNotEmpty(name)) {
//			map.put("name", name);
//		}
//		if (StringUtils.isNotEmpty(ip)) {
//			map.put("ip", ip);
//		}
		String cuPage = super.getRequest().getParameter("currentPage");
		Integer currentPage = 1;
		if(cuPage!=null){
			currentPage = Integer.valueOf(cuPage);
		}
		Page page = baseService.findAllByPageMysql(ClientInfo.class,map, "createDate", false, currentPage, super.getPageSize());
		super.getRequest().setAttribute("page", page); 
		return "queryClient";
	}
	
	public String  modifyClient() throws Exception {
		ClientInfo clientInfo = (ClientInfo) BeanUtil.getObject(super.getRequest(),ClientInfo.class);
		clientInfo.setCreateDate(new Date());
		baseService.update(clientInfo);
		return "queryIndex";
	}
	
	public String  getClient() throws Exception {
		String id = super.getRequest().getParameter("id");
		ClientInfo clientInfo = (ClientInfo) baseService.getObjectById(ClientInfo.class, id);
		super.getRequest().setAttribute("obj", clientInfo); 
		return "getClient";
	}
	
	public String  removeClient() throws Exception {
		String id = super.getRequest().getParameter("id");
		ClientInfo clientInfo = new ClientInfo();
		clientInfo.setId(Long.parseLong(id));
		clientInfo.setDeleteflag(1);
		baseService.update(clientInfo);
		return "queryIndex";
	}
	
	public String  addClient() throws Exception {
		ClientInfo clientInfo = (ClientInfo) BeanUtil.getObject(super.getRequest(), ClientInfo.class);
		clientInfo.setCreateDate(new Date());
		baseService.save(clientInfo);
		return "queryIndex";
	}
	
	public String  addUser() throws Exception {
		User user = (User) BeanUtil.getObject(super.getRequest(), User.class);
		user.setCreateDate(new Date());
		baseService.save(user);
		return "queryUserIndex";
	}
	
	
	
	//封装文件标题请求参数的属性
	private String title;
	//封装上传文件域的属性
	private File upload;
	//封装上传文件类型的属性
	private String uploadContentType;
	//封装上传文件名的属性
	private String uploadFileName;
	//接受依赖注入的属性
	private String savePath;
	//接受依赖注入的方法
	public void setSavePath(String savePath) {
	   this.savePath = savePath;
	}
	//返回上传文件的保存位置
	public String getSavePath() {
	   return ServletActionContext.getRequest().getRealPath(savePath);
	}
	//文件标题的set和get方法
	public String getTitle() {
	   return title;
	}
	public void setTitle(String title) {
	   this.title = title;
	}
	//上传文件对应文件内容的set和get方法
	public File getUpload() {
	   return upload;
	}
	public void setUpload(File upload) {
	   this.upload = upload;
	}
	//上传文件的文件类型的set和get方法
	public String getUploadContentType() {
	   return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
	   this.uploadContentType = uploadContentType;
	}
	//上传文件的文件名的set和get方法
	public String getUploadFileName() {
	   return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
	   this.uploadFileName = uploadFileName;
	}
	

	static final String FSP = System.getProperty("file.separator");
	private static final int BUFFER_SIZE = 16 * 1024; 
	private static void copyFile(File src, File dest) {
//		if(!dest.isDirectory()) {
//			dest.mkdirs();
//		}
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),
						BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dest),
						BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}
	
	private Boolean isAllowedExtensions(String extention) {
		if (".png,.bmp,.jpg,.doc,.xls".indexOf(extention) != -1) {
			return true;
		}
		return false;
	}
	
	private Boolean isAllowedSize(File file) {
		try {
			 FileInputStream fis = new FileInputStream(file) ;   
			 double mSize = fis.available()/1024/1024;
			 //0.5兆
			if (mSize<0.5) {
				return true;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	public String  addUserJson() throws Exception {
		JSONObject jObject = new JSONObject();
		jObject.put("success", false);
		System.out.println(uploadContentType);
		String fileName = getUploadFileName();
		String appendix = getExtention(fileName);
		boolean isAllowedSize = isAllowedSize(getUpload());
		if (isAllowedExtensions(appendix) && isAllowedSize) {
			String systemFileName = "upload-"+ System.currentTimeMillis() + appendix;
			String filePath = "upload" +  FSP+ systemFileName;
			String realPath = super.getRequest().getRealPath(FSP) + filePath;
			File destFile = new File(realPath);
			copyFile(getUpload(), destFile);
			String content = super.getRequest().getParameter("content");
			System.out.println("============\r\n"+content);
			User user = (User) BeanUtil.getObject(super.getRequest(), User.class);
			user.setCreateDate(new Date());
			try {
				baseService.save(user);
				jObject.put("success", true);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		} else if(!isAllowedSize){
			jObject.put("message", "文件过大");
		} else {
			jObject.put("message", "文件类型不支持");
		}
		PrintWriter pw = super.getPrintWriter();
		pw.append(jObject.toString());
		pw.flush();
		return null;
	}
	
	public String  removeUser() throws Exception {
		String id = super.getRequest().getParameter("id");
		User user = (User) baseService.getObjectById(User.class, id);
		user.setDeleteflag(1);
		baseService.update(user);
		return "queryUserIndex";
	}
	
	public String  queryUser() throws Exception {
		Map map = new HashMap<String, String>();
		map.put("deleteflag", 0);
//		if (StringUtils.isNotEmpty(name)) {
//			map.put("name", name);
//		}
//		if (StringUtils.isNotEmpty(ip)) {
//			map.put("ip", ip);
//		}
		String cuPage = super.getRequest().getParameter("currentPage");
		Integer currentPage = 1;
		if(cuPage!=null){
			currentPage = Integer.valueOf(cuPage);
		}
		Page page = baseService.findAllByPageMysql(User.class,map, "createDate", false, currentPage, super.getPageSize());
		super.getRequest().setAttribute("page", page); 
		return "queryUser";
	}
	
	public String  completeBox() throws Exception {
		JSONObject jObject = new JSONObject();
		jObject.put("success", true);
		List<User> list = baseService.getObjects(User.class);
		JSONArray jsonArray = new JSONArray();
		for (User user:list) {
			JSONObject tempObject = new JSONObject();
			tempObject.put("key", user.getUsername());
			tempObject.put("value", user.getPassword());
			tempObject.put("id", user.getId());
			jsonArray.add(tempObject);
		}
		jObject.put("datas", jsonArray);
		PrintWriter pw = super.getPrintWriter();
		pw.append(jObject.toString());
		System.out.println(jObject.toString());
		pw.flush();
		return null;
	}
	
	public String  queryUserJson() throws Exception {
		//easy ui gird
		String cuPage = super.getRequest().getParameter("page");
		String pSize = super.getRequest().getParameter("rows");
		String sort = super.getRequest().getParameter("sort");
		String order = super.getRequest().getParameter("order");
		System.out.println(order);
		
//		flexigrid String cuPage = super.getRequest().getParameter("currentPage");
//		String pSize = super.getRequest().getParameter("pageSize");
		Integer currentPage = 1;
		if(cuPage!=null){
			currentPage = Integer.valueOf(cuPage);
		}
		Integer pageSize = 10;
		if(pSize!=null){
			pageSize = Integer.valueOf(pSize);
		}
		Map map = new HashMap<String, String>();
		if (StringUtils.isNotEmpty(super.getRequest().getParameter("username"))) {
			map.put("username",super.getRequest().getParameter("username").trim());
		}
		if (StringUtils.isNotEmpty(super.getRequest().getParameter("password"))) {
			map.put("password",super.getRequest().getParameter("password").trim());
		}
		map.put("deleteflag", 0);
//		if (StringUtils.isNotEmpty(name)) {
//			map.put("name", name);
//		}
//		if (StringUtils.isNotEmpty(ip)) {
//			map.put("ip", ip);
//		}
		boolean orderBy = false;
		if (StringUtils.isEmpty(sort)) {
			sort = "createDate";
		} else {
			if (StringUtils.isNotEmpty(order)) {
				if (order.equals("asc")) {
					orderBy = true;
				}
			}
		}
		
		Page page = baseService.findAllByPageMysql(User.class,map, sort, orderBy, currentPage, pageSize);
		//格式化日期
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		//排除不需要转换到json的属性
		config.setExcludes(new String[]{"deleteflag","type"}); 
		JSONObject jObject = new JSONObject();
		jObject.put("page", page.getCurrentPage());
		jObject.put("total", page.getTotalRows());
		jObject.put("rows", JSONArray.fromObject(page.getData(), config));
		PrintWriter pw = super.getPrintWriter();
		pw.append(jObject.toString());
		System.out.println(jObject.toString());
		pw.flush();
		return null;
	}
	
	public String  modifyUser() throws Exception {
		User user = (User) BeanUtil.getObject(super.getRequest(),User.class);
		user.setCreateDate(new Date());
		baseService.update(user);
		return "queryUserIndex";
	}
	
	public String  getUser() throws Exception {
		String id = super.getRequest().getParameter("id");
		User user = (User) baseService.getObjectById(User.class, id);
		super.getRequest().setAttribute("obj", user); 
		return "getUser";
	}
}
